//
//  ShopDetailViewController.m
//  ZiJinLian
//
//  Created by 🐛 on 2017/3/25.
//  Copyright © 2017年 lzy. All rights reserved.
//

#import "ShopDetailViewController.h"
#import "ShopNameTableViewCell.h"
#import "SectionTwoTableViewCell.h"
#import "UIView+Extension.h"
#import "SDCycleScrollView.h"
#import "shopDetailView.h"
#import "ContentTableViewCell.h"
#import "SubmitOrderViewController.h"
#import "ZYBrowerView.h"
#import "ShareView.h"
#import "AppDelegate.h"
#import "DealersViewController.h"
#import "DetailModel.h"
#import "SpecWindowView.h"
@interface ShopDetailViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,SDCycleScrollViewDelegate,UIWebViewDelegate,ShareViewDelegate,QQShareDelegate>
//导航view
{
     AppDelegate *appdelegate;
}
@property (nonatomic ,strong) UIView      * navView;
@property (nonatomic ,strong) UIView      * v ;
@property (strong, nonatomic) UIView      * contentView;
@property (strong, nonatomic) UIView      * sigView;
@property (nonatomic,strong)  NSArray     * paramArray;
@property (nonatomic,strong)  UIWebView   * webView;
@property (nonatomic ,strong) UIImageView * backImag;
@property (nonatomic ,strong) UIImageView * wishedImag;
@property (nonatomic ,strong) UIImageView * shopImag;
@property (nonatomic ,strong) UITableView * tableView;
@property (strong, nonatomic) UIButton    * popBtn;
@property (strong, nonatomic) UIButton    * lastBtn;
@property (strong, nonatomic) UIButton    * siglastBtn;
//返回顶部的按钮
@property (strong, nonatomic) UIButton    * topBtn;
//选择商品详情跟规格的下划线
@property (strong, nonatomic) UILabel     * seleLabel;

@property (strong, nonatomic) NSString    * skuId;

@property (nonatomic,strong)  NSMutableArray      * heightArray;
@property (nonatomic,strong)  NSMutableDictionary * objDic;
@property (nonatomic ,strong) shopDetailView      *shopView;
@property (nonatomic ,strong) SDCycleScrollView   * cycleScrollView;
@property (nonatomic,assign)  BOOL      isCollect;
@property (assign, nonatomic) NSInteger index;
@property (assign, nonatomic) CGSize    size;
//确定是立即购买(10)还是 加入购物车 (20)
@property (assign, nonatomic) NSInteger statue;

@property (nonatomic,strong)  DetailModel  *   model;
//客服聊天页面的名字
@property ( copy, nonatomic) NSString    * nickname;
@property ( strong, nonatomic) SpecWindowView    * specView;

@end

@implementation ShopDetailViewController

-(NSMutableArray*)heightArray{
    if (!_heightArray) {
        _heightArray=[NSMutableArray array];
    }
    return _heightArray;
}
-(void)viewWillAppear:(BOOL)animated
{

    [super viewWillAppear:YES];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    if (@available(iOS 11.0, *)) {

        self.tableView.contentInsetAdjustmentBehavior=UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets=NO;
        // Fallback on earlier versions
    }
}

-(void)createView
{
    appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    //创建视图
    [self creatUI];
    
    //[self initTitle:@"33"];
    //创建返回按钮与分享按钮
    [self createdNavUI];
    //创建底部按钮
    [self creatBottomView];

    [self loadShopList];
    //[self initChooseView];
}

#pragma mark ------选择规格视图
-(void)initChooseView
{
    self.shadowView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, MainW, MainH)];
    self.shadowView.hidden=YES;
    self.shadowView.backgroundColor=[UIColor blackColor];
    self.shadowView.alpha=0.3;
    [self.view addSubview:self.shadowView];
    SpecWindowView * specView = [[NSBundle mainBundle]loadNibNamed:@"SpecWindowView" owner:nil options:nil].firstObject;
    [specView processData:self.objDic];
    
    specView.ImagsBackWithCloseWindow = ^(NSArray *Array) {
        [self seeImgClick:Array];
    };
    specView.CallBackWithCloseWindow = ^(NSString *type, NSString *goodsId,NSString * goodsNum) {
        [self dismiss];
        if ([type intValue]==0) {
            NSLog(@"取消%@",goodsId);
        }else if ([type intValue]==1){
            //确定]
            self.spuId=goodsId;
            [self addGoodsCartBtnClick:goodsNum];
            NSLog(@"%@",goodsId);
        }else{
            self.spuId=goodsId;
            [self nearBuyBtnClick:goodsNum];
            //立即购买
           NSLog(@"%@",goodsId);
        }
    };
    specView.frame = CGRectMake(0, MainH+10, MainW, MainH*2/3);
    self.specView=specView;
    [self.view addSubview:specView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss)];
    [self.shadowView addGestureRecognizer:tap];
}

#pragma mark ----附近购
-(void)nearBuyBtnClick:(NSString *)num{
    if (![self isLocationServiceOpen]) {
        LXAlertView *alert=[[LXAlertView alloc]initWithTitle:nil message:@"使用该功能需开启定位,是否立即开启?" cancelBtnTitle:@"取消" otherBtnTitle:@"确定" clickIndexBlock:^(NSInteger clickIndex) {
            if (clickIndex==1) {
                if (SYSTEM_VERSION_GREATER_THAN(@"8.0")) {
                    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                    if ([[UIApplication sharedApplication] canOpenURL:url]) {
                        [[UIApplication sharedApplication] openURL:url];
                    }
                } else {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=LOCATION_SERVICES"]];
                }
            }
        }];
        [alert showLXAlertView];
        return;
    }
    if ([ZJUserDefaultsTools isLogin]) {
        [self dismiss];
        NSMutableDictionary *dic=[[NSMutableDictionary   alloc]init];
        dic[@"skuId"]=self.spuId;
        dic[@"userId"]=[ZJUserDefaultsTools getCurrentUserID];
        //标注 ----------数量待定
        dic[@"number"]=num;
        [self doHttpRequestWithApi:API_SHOPBUYNOW_LIST method:POST dic:dic successBlock:^(NSDictionary *dic) {
            NSLog(@"%@",dic);
            NSString*string=[[NSUserDefaults standardUserDefaults] objectForKey:@"isShowAlert"];
            if ([string isEqualToString:@"提示"]||string==nil) {
                LXAlertView*alert=[[LXAlertView alloc]initWithTitle:nil message:@"匹配离您最近的经销商为您服务" cancelBtnTitle:@"不在提示" otherBtnTitle:@"确定" clickIndexBlock:^(NSInteger clickIndex) {
                    if (clickIndex==0) {
                        [[NSUserDefaults standardUserDefaults]setObject:@"不在提示" forKey:@"isShowAlert"];
                    }
                    DealersViewController*vc=[[DealersViewController alloc]init];
                    vc.factoryId=[NSString stringWithFormat:@"%@",self.model.skuId];
                    vc.orderDic=dic[@"data"];
                    [self.navigationController pushViewController:vc animated:YES];
                }];
                [alert showLXAlertView];
            }else{
                DealersViewController*vc=[[DealersViewController alloc]init];
                vc.factoryId=[NSString stringWithFormat:@"%@",self.model.skuId];
                vc.orderDic=dic[@"data"];
                [self.navigationController pushViewController:vc animated:YES];
            }
        }];
    }else{
        ZJLoginViewController *controller = [[ZJLoginViewController alloc] init];
        ZJBaseNavControllerViewController* nav=[[ZJBaseNavControllerViewController alloc]initWithRootViewController:controller];
        controller.modality=NO;
        [self presentViewController:nav animated:YES completion:nil];
    }
}
#pragma mark ----选择规格之后的完成按钮
-(void)addGoodsCartBtnClick:(NSString *)num{
    
    //10  立即购买  20  加入购物车
    if (self.statue==10) {
        if ([ZJUserDefaultsTools isLogin]) {
            [self dismiss];
            NSMutableDictionary *dic=[[NSMutableDictionary   alloc]init];
            dic[@"skuId"]=self.spuId;
            dic[@"userId"]=[ZJUserDefaultsTools getCurrentUserID];
            //////待定的数量
            dic[@"number"]=num;
            [self doHttpRequestWithApi:API_SHOPBUYNOW_LIST method:POST dic:dic successBlock:^(NSDictionary *dic) {
                NSLog(@"%@",dic);
                SubmitOrderViewController*vc=[[SubmitOrderViewController alloc]init];
                vc.orderDic=dic[@"data"];
                vc.styple=Description;
                [self.navigationController pushViewController:vc animated:YES];
            }];
        }else{
            ZJLoginViewController *controller = [[ZJLoginViewController alloc] init];
            ZJBaseNavControllerViewController* nav=[[ZJBaseNavControllerViewController alloc]initWithRootViewController:controller];
            controller.modality=NO;
            [self presentViewController:nav animated:YES completion:nil];
        }
    }else{
        if ([ZJUserDefaultsTools isLogin]) {
            [self dismiss];
            NSMutableDictionary *dic=[[NSMutableDictionary   alloc]init];
            dic[@"skuId"]=self.spuId;
            dic[@"userId"]=[ZJUserDefaultsTools getCurrentUserID];
            //第三处
            dic[@"number"]=num;
            [self doHttpRequestWithApi:API_ADDSHOPCAR_LIST method:POST dic:dic successBlock:^(NSDictionary *dic) {
                NSLog(@"%@",dic);
                [MBProgressHUD showSuccess:MyString(@"加入成功!")];
            }];
            
        }else{
            ZJLoginViewController *controller = [[ZJLoginViewController alloc] init];
            ZJBaseNavControllerViewController* nav=[[ZJBaseNavControllerViewController alloc]initWithRootViewController:controller];
            controller.modality=NO;
            [self presentViewController:nav animated:YES completion:nil];
        }
    }
    
}
-(void)dismiss
{
    [self.view endEditing:YES];
    self.shadowView.hidden=YES;;
    self.specView.collectionView.contentOffset = CGPointMake(0, 0);
    //    center.y = center.y+self.view.frame.size.height;
    [UIView animateWithDuration: 0.35 animations: ^{
        self.specView.frame =CGRectMake(0, MainH+10, MainW, MainH);
        
        //self.backgroundView.transform = CGAffineTransformIdentity;
    } completion: nil];
    
}
-(NSMutableArray *)rankArray{
    
    if (_rankArray == nil) {
        
        _rankArray = [[NSMutableArray alloc] init];
    }
    return _rankArray;
}
#pragma mark ------排序demo



#pragma mark -------创建底部按钮
-(void)creatBottomView{
    UIView*bottomView=[[UIView alloc]initWithFrame:CGRectMake(0, MainH-50, MainW, 50)];
    bottomView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:bottomView];
    UIImageView*kefuimag=[[UIImageView alloc]initWithFrame:CGRectMake(MainW/12-10, 6, 24,24 )];
    kefuimag.image=[UIImage imageNamed:@"icon_customer"];
    [bottomView addSubview:kefuimag];
    UILabel*kefuLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 30, MainW/6, 20)];
    kefuLabel.text=MyString(@"客服");
    kefuLabel.textColor=TextColor6;
    kefuLabel.font=FontAndStyle12;
    kefuLabel.textAlignment=1;
    [bottomView addSubview:kefuLabel];
    UIButton *kefubutton=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, MainW/6, 50)];
    //客服
    kefubutton.backgroundColor=[UIColor clearColor];
    [kefubutton addTarget:self action:@selector(kefuButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:kefubutton];
    UIImageView*collectimag=[[UIImageView alloc]initWithFrame:CGRectMake(MainW/4-10, 8, 20, 20)];
    self.wishedImag=collectimag;
    collectimag.image=[UIImage imageNamed:@"icon_collect_nor"];
    [bottomView addSubview:collectimag];
    UILabel*collectLabel=[[UILabel alloc]initWithFrame:CGRectMake(MainW/6, 30, MainW/6, 20)];
    collectLabel.text=MyString(@"收藏");
    collectLabel.textColor=TextColor6;
    collectLabel.font=FontAndStyle12;
    collectLabel.textAlignment=1;
    [bottomView addSubview:collectLabel];
    //收藏
    UIButton *clloectButton=[[UIButton alloc]initWithFrame:CGRectMake(MainW/6, 0, MainW/6, 50)];
    clloectButton.backgroundColor=[UIColor clearColor];
    [clloectButton addTarget:self action:@selector(clloectButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:clloectButton];
    //加入购物车
    UIButton *addShopButton=[[UIButton alloc]initWithFrame:CGRectMake(MainW/3, 0, MainW/3, 50)];
    [addShopButton setTitle:MyString(@"添加购物车") forState:UIControlStateNormal];
    [addShopButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [addShopButton.titleLabel setFont:FontAndStyle14];
    addShopButton.backgroundColor=HJ_Color(227, 82, 29);
    [addShopButton addTarget:self action:@selector(addShopButton) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:addShopButton];
    //立即购买
    UIButton *buyNowButton=[[UIButton alloc]initWithFrame:CGRectMake(MainW*2/3, 0, MainW/3, 50)];
    [buyNowButton setTitle:MyString(@"立即购买") forState:UIControlStateNormal];
    [buyNowButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [buyNowButton.titleLabel setFont:FontAndStyle14];
    buyNowButton.backgroundColor=UIColorFromRGB(0xcf0000);
    [buyNowButton addTarget:self action:@selector(buyNowButton) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:buyNowButton];
    self.topBtn=[[UIButton alloc]init];
    self.topBtn.frame= CGRectMake(MainW-50, MainH-100, 40, 40);
    self.topBtn.hidden=YES;
    [self.topBtn setBackgroundImage:[UIImage imageNamed:@"icon_top"] forState:UIControlStateNormal];
    [self.topBtn addTarget:self action:@selector(backTopClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.topBtn];
//    [self showMessage:@"asdasd"];
//    [self showToast:@"nihao"];
//    NSMutableDictionary*dic=[[NSMutableDictionary alloc]init];
//    [dic setObject:@"sd" forKey:@"dsa"];
//    [self doHttpRequestWithApi:API_AREA method:POST dic:dic successBlock:^(NSDictionary *dic) {
//        
//    }];
}
#pragma mark -------回顶部
-(void)backTopClick{
    [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES]; 
    
}
#pragma mark -------客服
-(void)kefuButtonClick{
    if ([ZJUserDefaultsTools isLogin]) {
    EaseMessageViewController *chatController = [[EaseMessageViewController alloc] initWithConversationChatter:[NSString stringWithFormat:@"%@",self.model.sellerId] conversationType:EMConversationTypeChat];
        chatController.title=[NSString stringWithFormat:@"%@",self
                              .nickname];
        [self.navigationController pushViewController:chatController animated:YES];
        NSLog(@"客服");
    }else{
        ZJLoginViewController *controller = [[ZJLoginViewController alloc] init];
        ZJBaseNavControllerViewController* nav=[[ZJBaseNavControllerViewController alloc]initWithRootViewController:controller];
        controller.modality=NO;
        [self presentViewController:nav animated:YES completion:nil];
    }
    
}
#pragma mark -------收藏
-(void)clloectButtonClick{
    if ([ZJUserDefaultsTools isLogin]) {
        if (self.isCollect==NO) {
            [self addCollect];
        }else{
            [self removeCollect];
        }
    }else{
        ZJLoginViewController *controller = [[ZJLoginViewController alloc] init];
        ZJBaseNavControllerViewController* nav=[[ZJBaseNavControllerViewController alloc]initWithRootViewController:controller];
        controller.modality=NO;
        [self presentViewController:nav animated:YES completion:nil];
    }

    
    NSLog(@"收藏");
}
#pragma mark -------立即购买
-(void)buyNowButton{
    self.shadowView.hidden=NO;
    [UIView animateWithDuration: 0.35 animations: ^{
        self.specView.frame =CGRectMake(0, MainH/3, MainW, MainH*2/3);
        if ([self.objDic[@"data"][@"nearBy"] intValue]==1) {
            self.specView.leftBtn.bsg_width=MainW/2;
            self.specView.rightBtn.bsg_width=MainW/2;
            self.specView.rightBtn.bsg_x=MainW/2;
        }else{
            self.specView.leftBtn.bsg_width=0;
            self.specView.rightBtn.bsg_width=MainW;
            self.specView.rightBtn.bsg_x=0;
        }
        [LoadMaskHelper showMaskWithType:RealIncome onView:self.view delay:0.5];
       
    } completion: nil];
    self.statue=10;
}
#pragma mark -------加入购物车
-(void)addShopButton{
    self.shadowView.hidden=NO;
    [UIView animateWithDuration: 0.35 animations: ^{
        self.specView.frame =CGRectMake(0, MainH/3, MainW, MainH*2/3);
        self.specView.leftBtn.bsg_width=0;
        self.specView.rightBtn.bsg_width=MainW;
        self.specView.rightBtn.bsg_x=0;
         [LoadMaskHelper showMaskWithType:RealIncome onView:self.view delay:0.5];
    } completion: nil];
    self.statue=20;
}
-(void)creatUI{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, MainW, MainH-50) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor=Gray_Color;
    [self.view addSubview:self.tableView];
    self.index=1;
    [self creatSigment];
    [self.tableView registerNib:[UINib nibWithNibName:@"ShopNameTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"ShopNameTableViewCell"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"SectionTwoTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"SectionTwoTableViewCell"];
    [self.tableView registerClass:[ContentTableViewCell class] forCellReuseIdentifier:kCellIdentifier];
   
}
#pragma mark ----  导航按钮
- (void)createdNavUI
{  //返回手势
    self.navView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, MainW, 64)];
    self.navView.backgroundColor=[UIColor whiteColor];
    self.navView.alpha=0.0;
    [self.view addSubview:self.navView];
    UITapGestureRecognizer * backTapgest = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backBtnClick)];
    //购物车手势
    UITapGestureRecognizer * shopTapgest = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(shopBtnClick)];
    self.backImag=[[UIImageView alloc]initWithFrame:CGRectMake(10, 24, 30, 30)];
     self.backImag.image=[UIImage imageNamed:@"back_black"];
    [self.view addSubview:self.backImag];
     self.backImag.userInteractionEnabled = YES;
    [self.backImag addGestureRecognizer:backTapgest];
    self.shopImag=[[UIImageView alloc]initWithFrame:CGRectMake(MainW-40, 24, 30, 30)];
     self.shopImag.image=[UIImage imageNamed:@"shopping_black"];
    [self.view addSubview:self.shopImag];
     self.shopImag.userInteractionEnabled = YES;
    [self.shopImag addGestureRecognizer:shopTapgest];
    ViewRadius(self.backImag, 15);
    ViewRadius(self.shopImag, 15);
    self.v=[ZJUITools getCutLine];
    self.v.frame=CGRectMake(0, 64, MainW, 1);
    self.v.hidden=YES;
    [self.view addSubview:self.v];
}

-(void)backBtnClick{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark -----进入购物车
-(void)shopBtnClick{
    NSLog(@"购物车");
    MianTabBarViewController *tabbar = [[MianTabBarViewController alloc] init];
    [tabbar setSelectedIndex:2];
    [UIApplication sharedApplication].keyWindow.rootViewController = tabbar;
}

#pragma mark ------------ delegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            return 5;
            break;
        case 1:
            return 0.01;
            break;
        default:
            return 0;
            break;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            return 0.01;
            break;
        case 1:
            return 49;
            break;
        default:
            return 0;
            break;
    }
    //return 0;
}
#pragma mark -----去除表头悬停效果
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if(scrollView == self.tableView) {
        //CGFloat sectionHeaderHeight = 50;
        if (scrollView.contentOffset.y>=MainH/4-84) {
            
            self.navView.alpha=1.0;
            self.v.hidden=NO;
            self.backImag.image=[UIImage imageNamed:@"back_white"];
            self.shopImag.image=[UIImage imageNamed:@"shopping_white"];
        } else if (scrollView.contentOffset.y<MainH/4-84) {
            self.backImag.image=[UIImage imageNamed:@"back_black"];
            self.shopImag.image=[UIImage imageNamed:@"shopping_black"];
            self.navView.alpha=0.0;
            self.v.hidden=YES;
        }
        if (scrollView.contentOffset.y>=MainH*1.5) {
            self.topBtn.hidden=NO;
        }else{
            self.topBtn.hidden=YES;
        }
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section ==1){
        if (self.index==1) {
            if (self.model.detail.count==0) {
                return 44;
            }else{
                //CGSize size=[ZJUITools getImageSizeWithURL:self.detailArray[indexPath.row]];
                if (self.heightArray.count!=self.model.detail.count) {
                    return MainW;
                }else{
                    CGFloat height=[self.heightArray[indexPath.row] floatValue];
                    
                    if(isnan(height)){      //isnan为系统函数
                        
                        return height;
                    }
                    else {
                        //you code
                        return height;
                    }
                }
                
                
            }
            
        }
        return 44;
    }else if (indexPath.section ==0&&indexPath.row ==0){
        return MainW;
    }else if (indexPath.section ==0&&indexPath.row ==1){
        CGFloat height =[ZJUITools getHeightByWidth:self.view.frame.size.width-20 title:self.model.intro font:FontAndStyle12];
        if (self.model.tags.count==0&&self.model.serves.count==0) {
            height=height+135;
            return height;
        }else if (self.model.tags.count==0||self.model.serves.count==0){
            height=height+140;
            return height;
        }else if (self.model.tags.count!=0&&self.model.serves.count!=0){
            height=height+165;
            return height;
        }else{
            return height;
        }
        
    }
    else{
        return MainH;
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            return 2;
            break;
        case 1:
            if (self.index==1) {
                return self.model.detail.count;
            }
            return self.paramArray.count;
            break;
        default:
            return 1;
            break;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * hjID = [NSString stringWithFormat:@"%ldcell%ld",indexPath.section,indexPath.row];
    UITableViewCell * hjcell = [tableView dequeueReusableCellWithIdentifier:hjID];
    if (!hjcell) {
        hjcell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:hjID];
    }
    switch (indexPath.section) {
        case 0:{
            if (indexPath.row==1) {
                ContentTableViewCell*cell=[tableView dequeueReusableCellWithIdentifier:kCellIdentifier forIndexPath:indexPath];
                [cell setModel:self.model];
                [cell.shareBtn addTarget:self action:@selector(shareBtnClick) forControlEvents:UIControlEventTouchUpInside];
                return cell;
            }else{
                self.cycleScrollView.imageURLStringsGroup=self.model.banner;
                [hjcell addSubview:self.cycleScrollView];
                hjcell.selectionStyle = UITableViewCellSelectionStyleNone;
                return hjcell;
            }
        }
            break;
        case 1:{
            // 视频
            if (self.index==1) {
                SectionTwoTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"SectionTwoTableViewCell" forIndexPath:indexPath];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                //}
                [cell.detaiImg sd_setImageWithURL:[NSURL URLWithString:self.model.detail[indexPath.row]] placeholderImage:[UIImage imageNamed:@"placeholderImage"]];
        
                return cell;
                
            }else{
                tableView.separatorStyle =UITableViewCellSeparatorStyleSingleLine;
                tableView.separatorColor =SeparatorColor;
                //tableView.separatorInset=UIEdgeInsetsZero;
                hjcell.textLabel.text=[NSString stringWithFormat:@"%@: %@",self.paramArray[indexPath.row][@"k"],self.paramArray[indexPath.row][@"v"]];
                hjcell.textLabel.font=FontAndStyle12;
                hjcell.textLabel.textColor=TextColor3;
                
            }
            return hjcell;
        }
            break;
            
        default:
        {
            SectionTwoTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"SectionTwoTableViewCell" forIndexPath:indexPath];
            return cell;
        }
            break;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
        case 2:
            NSLog(@"正品??");
            break;
            
        default:
            break;
    }
    
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section==1) {
        return self.sigView;
    }
    return nil;
}
#pragma mark ---加载选择项 防止重复加载
-(void)creatSigment{
    self.webView=[[UIWebView alloc]init];
    self.webView.delegate=self;
    SDCycleScrollView *cycle=[SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, MainW, MainW)delegate:self placeholderImage:[UIImage imageNamed:@"placeholderImage"]];
    cycle.bannerImageViewContentMode=UIViewContentModeScaleAspectFill;
    cycle.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    cycle.autoScrollTimeInterval =3.;
    self.cycleScrollView=cycle;
    //[self addSubview:_cycleScrollerView];
        UIView*view=[[UIView alloc]init];
        NSArray *arry=[NSArray arrayWithObjects:MyString(@"图文详情"),MyString(@"规格列表"), nil];
        view.backgroundColor=[UIColor whiteColor];
    for (int i=0; i<2; i++)
    {
        UIButton*tuButton=[[UIButton alloc]initWithFrame:CGRectMake(0+MainW/2*i, 12, MainW/2, 25)];
        //tuButton.backgroundColor=[UIColor whiteColor];
        [tuButton setTitle:arry[i] forState:UIControlStateNormal];
        [tuButton.titleLabel setFont:FontAndStyle14];
        [tuButton setTitleColor:TextColor3 forState:UIControlStateNormal];
        [tuButton setTitleColor:Red_Color forState:UIControlStateSelected];
        if (i==0) {
            tuButton.selected=YES;
            self.siglastBtn=tuButton;
            self.siglastBtn.backgroundColor=[UIColor whiteColor];
    }
        tuButton.tag=i+100;
        [tuButton addTarget:self action:@selector(refreshLoadata:) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:tuButton];
    }
        NSString*string= @"商品详情";
        self.size=[string sizeWithAttributes:@{NSFontAttributeName:FontAndStyle14}];
        _seleLabel=[[UILabel alloc]initWithFrame:CGRectMake(MainW/4-self.size.width/2, 48, self.size.width, 1)];
        _seleLabel.backgroundColor=Red_Color;
        [view addSubview:_seleLabel];
        self.sigView=view;
}
-(void)refreshLoadata:(UIButton *)sender{
    if (sender.tag==100) {
        self.seleLabel.frame=CGRectMake(MainW/4-self.size.width/2, 48, self.size.width, 1);
        self.index=1;
    }else{
        self.seleLabel.frame=CGRectMake(MainW*3/4-self.size.width/2, 48,self.size.width, 1);
        self.index=2;
    }
    if (sender!=self.siglastBtn) {
        self.siglastBtn.selected=NO;
        sender.selected=YES;
        self.siglastBtn=sender;
    }else{
        self.siglastBtn.selected = YES;
    }
        [self.tableView reloadData];
    
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
        UIView*view=[[UIView alloc]init];
        view.backgroundColor=Gray_Color;
        return view;
}
#pragma mark ------分享
-(void)shareBtnClick{
        self.shadowView.hidden=NO;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(Sharedismiss)];
        self.share=[[ShareView alloc]initWithFrame:CGRectMake(0, 0, MainW, MainH)];
        self.share.delegate=self;
        [self.view addSubview:self.share];
        [self.share.alphaView addGestureRecognizer:tap];
        [UIView animateWithDuration:0.35 animations:^{
        self.share.mainView.frame=CGRectMake(0, MainH-250, MainW, 250);
        }];
}
-(void)Sharedismiss{
    self.shadowView.hidden=YES;
    [UIView animateWithDuration:0.35 animations:^{
        self.share.mainView.frame=CGRectMake(0, MainH, MainW, 250);
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.share.hidden=YES;
    });
}
-(void)cancleShareClick{
    [self Sharedismiss];
}
-(void)chooseShareToWhich:(FL_Button *)sender{
    [self Sharedismiss];
    switch (sender.tag) {
        case 100:
        {
            [self shareTofriend];

        }
            break;
        case 101:
        {
            [self shareTextToWechat];

        }
            break;
        case 102:
        {
            NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/tm/item/sku/detail?skuId=%@",baseURL,self.spuId]];
            NSURL *preimageUrl = [NSURL URLWithString:self.model.banner[0]];
            QQApiNewsObject* img = [QQApiNewsObject objectWithURL:url title:self.model.title description:[NSString stringWithFormat:@"%@",self.model.intro] previewImageURL:preimageUrl];
            
            //请求帮助类,分享的所有基础对象，都要封装成这种请求对象。
            SendMessageToQQReq* req = [SendMessageToQQReq reqWithContent:img];
            QQApiSendResultCode sent = [QQApiInterface sendReq:req];
            
            //通过自定义的qqdelegate来通知本controller，是否成功分享
            appdelegate.qqDelegate = self;
            NSLog(@"QQApiSendResultCode %d",sent);
            
            [self handleSendResult:sent];
        }
            break;
        case 103:
        {
            NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/tm/item/sku/detail?skuId=%@",baseURL,self.spuId]];
            NSURL *preimageUrl = [NSURL URLWithString:self.model.banner[0]];
            QQApiNewsObject* img = [QQApiNewsObject objectWithURL:url title:self.model.title description:[NSString stringWithFormat:@"%@",self.model.intro] previewImageURL:preimageUrl];
            
            //请求帮助类,分享的所有基础对象，都要封装成这种请求对象。
            SendMessageToQQReq* req = [SendMessageToQQReq reqWithContent:img];
            QQApiSendResultCode sent = [QQApiInterface SendReqToQZone:req];
            
            //通过自定义的qqdelegate来通知本controller，是否成功分享
            appdelegate.qqDelegate = self;
            NSLog(@"QQApiSendResultCode %d",sent);
            
            [self handleSendResult:sent];
        }
            break;
            
        default:
            break;
    }
}
-(void)shareSuccssWithQQCode:(NSInteger)code{
    NSLog(@"code %ld",(long)code);
    if (code == 0) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD showSuccess:MyString(@"分享成功")];
        });
        
    }else{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD showError:MyString(@"分享失败")];
        });
        
    }
}
- (void)handleSendResult:(QQApiSendResultCode)sendResult
{
    switch (sendResult)
    {
        case EQQAPIAPPNOTREGISTED:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"App未注册" delegate:nil cancelButtonTitle:MyString(@"取消") otherButtonTitles:nil];
            [msgbox show];
            
            
            break;
        }
        case EQQAPIMESSAGECONTENTINVALID:
        case EQQAPIMESSAGECONTENTNULL:
        case EQQAPIMESSAGETYPEINVALID:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"发送参数错误" delegate:nil cancelButtonTitle:MyString(@"取消") otherButtonTitles:nil];
            [msgbox show];
            
            
            break;
        }
        case EQQAPIQQNOTINSTALLED:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"未安装手Q" delegate:nil cancelButtonTitle:MyString(@"取消") otherButtonTitles:nil];
            [msgbox show];
            
            
            break;
        }
        case EQQAPIQQNOTSUPPORTAPI:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"API接口不支持" delegate:nil cancelButtonTitle:MyString(@"取消") otherButtonTitles:nil];
            [msgbox show];
            
            
            break;
        }
        case EQQAPISENDFAILD:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"发送失败" delegate:nil cancelButtonTitle:MyString(@"取消") otherButtonTitles:nil];
            [msgbox show];
            
            
            break;
        }
        case EQQAPIVERSIONNEEDUPDATE:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"当前QQ版本太低，需要更新" delegate:nil cancelButtonTitle:MyString(@"取消") otherButtonTitles:nil];
            [msgbox show];
            break;
        }
        default:
        {
            break;
        }
    }
}
- (void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
}
#pragma mark -------------- 商品选购页面
-(void)loadBuyShopView{
    self.isShowDiag=NO;
    NSMutableDictionary*dic=[[NSMutableDictionary alloc]init];
    dic[@"skuId"]=self.spuId;
	dic[@"userId"] =[ZJUserDefaultsTools getCurrentUserID];
    [ self doHttpRequestWithApi:API_SHOPBUY_LIST method:GET dic:dic successBlock:^(NSDictionary *dic) {
        NSLog(@"**********%@",dic[@"data"][@"name"]);
        self.objDic=[dic copy];
        [self initChooseView];
    }];
}
#pragma mark -------------- 商品详情
- (void)loadShopList
{
//    self.isShowDiag=NO;
//    [self showDialog];
    NSMutableDictionary*dic=[[NSMutableDictionary alloc]init];
    dic[@"skuId"]=self.spuId;
    dic[@"userId"]=[ZJUserDefaultsTools getCurrentUserID];
    [self doHttpRequestWithApi:API_SHOPDETAIL_LIST method:POST dic:dic successBlock:^(NSDictionary *dic) {
        DetailModel *model=[DetailModel mj_objectWithKeyValues:dic[@"data"]];
        NSLog(@"---%@",model.intro);
        self.model=model;
        //写反了赋值(self.sku  和 self.spu是相反的)
        self.skuId=model.spuId;
        [self loadImInfo:[NSString stringWithFormat:@"%@",model.sellerId]];
        if ([model.wished intValue]==0) {
            self.wishedImag.image=[UIImage imageNamed:@"icon_collect_nor"];
            self.isCollect=NO;
        }else{
            self.isCollect=YES;
            self.wishedImag.image=[UIImage imageNamed:@"icon_collect_pre"];
        }
        NSMutableString *string=model.param;
        self.paramArray=[ZJUITools jsonDic:string];
        [self.tableView reloadData];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self dismissDialog];
        });
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            for (NSString *string in model.detail) {
                CGSize size=[ZJUITools getImageSizeWithURL:string];
                CGFloat height=size.height*(MainW/size.width);
                if (!isnan(height)) {
                    [self.heightArray addObject:[NSString stringWithFormat:@"%f",height]];
                }else{
                    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:string]];
                    UIImage *image = [UIImage imageWithData:data];
                    CGSize imgSize = image.size;
                    CGFloat height=imgSize.height*(MainW/imgSize.width);
                    [self.heightArray addObject:[NSString stringWithFormat:@"%f",height]];
                    
                }
                
            }
            [self.tableView reloadData];
            
        });
        
        [self loadBuyShopView];
        
    }];
}

#pragma  mark----查看大图----
-(void)seeImgClick:(NSArray *)imagesUrlAry{
    if (imagesUrlAry.count==0) {
        [self showToast:MyString(@"暂无详情图")];
        return;
    }
    ZYBrowerView *browerView = [[ZYBrowerView alloc] initWithFrame:[UIScreen mainScreen].bounds imagesUrlAry:imagesUrlAry currentIndex:0];
    [browerView show];
}
#pragma mark-----添加收藏------
-(void)addCollect{
    NSMutableDictionary*dic=[[NSMutableDictionary alloc]init];
    dic[@"userId"]=[ZJUserDefaultsTools getCurrentUserID];
    dic[@"spuId"]=self.model.spuId;;
    dic[@"skuId"]=self.model.skuId;;
    [ self doHttpRequestWithApi:API_SHOPADDCOLLECT method:GET dic:dic successBlock:^(NSDictionary *dic) {
        NSLog(@"添加结果%@",dic);
        [MBProgressHUD showSuccess:dic[@"msg"]];
        self.isCollect=YES;
        self.wishedImag.image=[UIImage imageNamed:@"icon_collect_pre"];
        
    }];

}
#pragma mark-----删除收藏------
-(void)removeCollect{
    NSMutableDictionary*dic=[[NSMutableDictionary alloc]init];
    dic[@"userId"]=[ZJUserDefaultsTools getCurrentUserID];
    dic[@"spuId"]=self.model.spuId;
    dic[@"skuId"]=self.model.skuId;
    [ self doHttpRequestWithApi:API_SHOPREMOVECLT method:GET dic:dic successBlock:^(NSDictionary *dic) {
        [MBProgressHUD showSuccess:dic[@"msg"]];
        self.isCollect=NO;
        self.wishedImag.image=[UIImage imageNamed:@"icon_collect_nor"];
    }];
}
-(void)loadImInfo:(NSString *)merchantId{
    ///api/member/chat/info
    self.isShowDiag=NO;
    NSMutableDictionary*dic=[[NSMutableDictionary alloc]init];
    //dic[@"userId"]=[ZJUserDefaultsTools getCurrentUserID];
    dic[@"merchantId"]=merchantId;
    [ self doHttpRequestWithApi:CHATINFO method:GET dic:dic successBlock:^(NSDictionary *dic) {
        self.nickname=dic[@"data"][@"nickname"];
        NSLog(@"-------%@",dic);
    }];
}
//微信好友
-(void)shareTofriend{
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    //创建网页内容对象
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:self.model.title descr:self.model.intro thumImage:self.model.banner[0]];
    //设置网页地址
    shareObject.webpageUrl =[NSString stringWithFormat:@"%@/tm/item/sku/detail?skuId=%@",baseURL,self.spuId];
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_WechatSession messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            NSLog(@"************Share fail with error %@*********",error);
        }else{
            NSLog(@"response data is %@",data);
        }
    }];
}
//微信朋友圈
- (void)shareTextToWechat
{
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    //创建网页内容对象
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:self.model.title descr:self.model.intro thumImage:self.model.banner[0]];
    //设置网页地址
    shareObject.webpageUrl =[NSString stringWithFormat:@"%@/tm/item/sku/detail?skuId=%@",baseURL,self.spuId];
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_WechatTimeLine messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            NSLog(@"************Share fail with error %@*********",error);
        }else{
            NSLog(@"response data is %@",data);
        }
    }];
}
-(BOOL)isLocationServiceOpen {
    if ([ CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
        return NO;
    } else
        return YES;
}
@end
